package com.cloud.grainmall.cart.interceptor;

import com.cloud.common.constant.AuthServerConstant;
import com.cloud.common.vo.MemberRespVo;
import com.cloud.grainmall.cart.constant.CartConstant;
import com.cloud.grainmall.cart.to.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 在执行方法前，判断登录状态，封装传递给controller，采用threadLocal机制
 * @author lisw
 * @create 2021/7/17 9:52
 */
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response
            , Object handler) throws Exception {
        UserInfoTo infoTo = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberRespVo member = (MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (member != null){
            //登录之后封装UserID
            infoTo.setUserId(member.getId());
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null){
            for (Cookie cookie : cookies) {
                //user-key
                String name = cookie.getName();
                if (name.equals(CartConstant.TEMP_USER_COOKIE_NAME)){
                    infoTo.setUserKey(cookie.getValue());
                }
            }
        }
        //在临时用户没有key的时候，给临时用户分配一个key
        if (StringUtils.isEmpty(infoTo.getUserKey())){
            String uuid = UUID.randomUUID().toString();
            infoTo.setUserKey(uuid);
            infoTo.setTempKey(true);
        }
        //目标方法执行之前
        threadLocal.set(infoTo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (threadLocal.get().getUserId() == null){
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, threadLocal.get().getUserKey());
            cookie.setDomain("grainmall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIME);
            response.addCookie(cookie);
        }
    }
}
